package com.srb.core.controller.api;


import com.srb.base.util.JwtUtils;
import com.srb.common.exception.Assert;
import com.srb.common.result.R;
import com.srb.common.result.ResponseEnum;
import com.srb.common.util.RegexValidateUtils;
import com.srb.core.pojo.vo.LoginVo;
import com.srb.core.pojo.vo.RegisterVo;
import com.srb.core.pojo.vo.UserInfoVo;
import com.srb.core.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author dapeng
 * @since 2021-08-08
 */
@Api(tags = {"会员接口"})
@Slf4j
@RestController
//@CrossOrigin
@RequestMapping("/api/core/userInfo")
public class ApiUserInfoController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "会员注册")
    @PostMapping(value = "/register")
    public R register(@RequestBody RegisterVo registerVo){
        Assert.notEmpty(registerVo.getMobile(), ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(registerVo.getPassword(), ResponseEnum.PASSWORD_NULL_ERROR);
        Assert.notEmpty(registerVo.getCode(),ResponseEnum.CODE_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(registerVo.getMobile()),ResponseEnum.MOBILE_ERROR);
        //校验验证码是否正确
        String codeGen = redisTemplate.opsForValue().get("srb:sms:code:" + registerVo.getMobile()).toString();
        Assert.equals(registerVo.getCode(),codeGen, ResponseEnum.CODE_ERROR);
        //注册
        userInfoService.register(registerVo);
        return R.ok().message("注册成功");
    }

    @ApiOperation(value = "会员登录")
    @PostMapping(value = "/login")
    public R login(@RequestBody LoginVo loginVo, HttpServletRequest request){
        Assert.notEmpty(loginVo.getMobile(), ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(loginVo.getPassword(), ResponseEnum.PASSWORD_NULL_ERROR);
        String ip = request.getRemoteAddr();
        UserInfoVo userInfoVo = userInfoService.login(loginVo,ip);
        return R.ok().data("userInfo",userInfoVo);
    }

    @ApiOperation(value = "校验令牌")
    @GetMapping(value = "/checkToken")
    public R checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean result = JwtUtils.checkToken(token);
        if (result) {
            return R.ok();
        }else {
            return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
        }
    }

    @ApiOperation(value = "校验手机号是否被注册")
    @GetMapping(value = "/checkMobile/{mobile}")
    public boolean checkMobile(@PathVariable(value = "mobile") String mobile){
        return userInfoService.checkMobile(mobile);
    }
}

